package com.yuke.cloud.service.tmc.controller.frontend;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.uac.dto.UserInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.tmc.entity.TmcChat;
import com.yuke.cloud.service.tmc.service.TmcChatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* Created by zn on 2020/01/10.
*/
@Slf4j
@Api(value = "WEB - TmcChatController", tags = "处理TmcChat相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/chat")
public class TmcChatController extends BaseController {
    @Resource
    private TmcChatService tmcChatService;
    @Autowired
    private SimpUserRegistry userRegistry;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UacUserFeignApi uacUserFeignApi;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "tmcChat", value = "该数据记录的POJO") @RequestBody TmcChat tmcChat) {
        tmcChatService.save(tmcChat);
        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        tmcChatService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "tmcChat", value = "需要修改的内容") @RequestBody TmcChat tmcChat) {
        tmcChatService.update(tmcChat);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<TmcChat> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        TmcChat tmcChat = tmcChatService.findById(id);
        return WrapMapper.ok(tmcChat);
    }

    @PostMapping("/chatList")
    @ApiOperation(httpMethod = "POST", value = "分页条件获取聊天记录")
    public Wrapper<PageInfo<TmcChat>> list(@ApiParam(name = "tmcChat", value = "需要的内容") @RequestBody JSONObject jsonObject) {
        //{"page":0,"size":5,"tmcChat":{"sendId":1,"receiveId":271357058761228288,"msgType":0}}
        Integer page = jsonObject.getInteger("page");
        Integer size = jsonObject.getInteger("size");
        PageHelper.startPage(page, size);

        JSONObject json = jsonObject.getJSONObject("tmcChat");

        TmcChat tmcChat = new TmcChat();
        tmcChat.setSendId(Long.parseLong(json.get("sendId").toString()));
        tmcChat.setReceiveId(Long.parseLong(json.get("receiveId").toString()));
        if (PublicUtil.isNotEmpty(json.get("msgType"))){
            tmcChat.setMsgType(Byte.valueOf(json.get("msgType").toString()));
        }else{
            tmcChat.setMsgType((byte)0);
        }
        List<TmcChat> list = tmcChatService.selectChatList(tmcChat);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 获得websocket连接信息   @SendToUser  @SubscribeMapping("/SubscribeMapping")
     * userType   0:用户，1：管理员
     * @return
     */

    @RequestMapping(path = "/getRegistry", method = RequestMethod.GET)
    public  Wrapper<PageInfo<UserInfoDto>> getRegistry(@ApiParam(name = "userType", value = "标记", defaultValue = "0") @RequestParam(defaultValue = "0") Integer userType,
                                                       @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                       @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        System.out.println("获得websocket连接信息:"+userRegistry.getUsers());
        List<Long> userName = new ArrayList<>();
        for (SimpUser user : userRegistry.getUsers()) {
            log.info("userName : " + user.getName() + ", userSession : " + user.getSessions().toString());

            //解析获取用户信息
            if (PublicUtil.isNotEmpty(user.getName())) {
                if (user.getName().length() > 20){
                    continue;
                }
                Long userId = Long.parseLong(user.getName());
                userName.add(userId);
            }
        }
        System.out.println("在线用户ID"+userName);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("page",page);
        jsonObject.put("size",size);
        jsonObject.put("userType",userType);
        jsonObject.put("userIds",userName);

        Wrapper<PageInfo<UserInfoDto>> userInfoDtoWrapper = uacUserFeignApi.getUserPageByUserIds(jsonObject);

        return userInfoDtoWrapper;
    }

    /**
     * 服务端向用户端发送消息
     * @return
     */

    @MessageMapping("/sendMsg")
    public TmcChat userTest(TmcChat message) {
        //保存服务端回应的消息
        message.setChatId(generateId());
        message.setMsgType((byte)0);
        message.setCreateTime(new Date());
        tmcChatService.save(message);

        //向目标发送消息
        messagingTemplate.convertAndSendToUser(message.getReceiveId().toString(), "/queue/message", message);
        return message;
    }

    /**
     * 表示服务端发送广播消息，客户端需要在主题"/topic/boastMsg"上监听并接收服务端发回的消息
     *
     */
    @MessageMapping("/boastMsg")
    @SendTo("/topic/boastMsg")
    public TmcChat greeting(TmcChat message) throws Exception {
        System.out.println("/hello相应"+message.getChatMsg());
        message.setChatId(generateId());
        message.setMsgType((byte)1);
        message.setCreateTime(new Date());
        tmcChatService.save(message);
        return message;
    }

    /**
     * 用户端向服务端发送消息
     * @return
     */
    @MessageMapping("/startChat")
    public TmcChat startChat(TmcChat message) {

        //保存服务端回应的消息
        message.setChatId(generateId());
        message.setReceiveId(1L);
        message.setReceiveName("admin");
        message.setMsgType((byte)0);
        message.setCreateTime(new Date());
        tmcChatService.save(message);

        //向目标发送消息
        messagingTemplate.convertAndSendToUser("1", "/queue/message", message);
        return message;
    }
}
